<template>
  <div class="mail-root">
    <!-- 左侧导航栏 -->
    <div class="mail-sider">
      <template v-if="!hasBindEmail">
        <div class="mail-empty">
          <el-image :src="mailIcon" style="width: 88px; margin-bottom: 18px;" />
          <div style="font-size:16px; color: #666; margin-bottom: 8px;">您尚未绑定邮箱</div>
          <el-link type="danger" @click="dialogVisible = true">点击立即绑定</el-link>
        </div>
      </template>
      <template v-else>
        <div style="padding: 18px 10px 6px 10px;">
          <el-button type="danger" icon="el-icon-edit" round size="small" style="width:100%;margin-bottom: 8px;">写邮件</el-button>
          <el-dropdown>
            <el-button size="small" style="width:100%;">收信 <i class="el-icon-arrow-down"></i></el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>收取所有</el-dropdown-item>
                <el-dropdown-item>仅收未读</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <el-menu class="mail-menu" :default-active="currentFolder" :default-openeds="defaultOpeneds" @select="handleFolderSelect">
          <el-sub-menu index="common">
            <template #title>常用文件夹</template>
            <el-menu-item index="all">所有未读</el-menu-item>
            <el-menu-item index="star">星标邮件</el-menu-item>
            <el-menu-item index="tag">标签邮件</el-menu-item>
          </el-sub-menu>
          <el-sub-menu :index="mailAccount">
            <template #title>{{ mailAccount }}</template>
            <el-menu-item index="inbox">收件箱</el-menu-item>
            <el-menu-item index="sent">已发送</el-menu-item>
            <el-menu-item index="draft">草稿箱</el-menu-item>
            <el-menu-item index="deleted">已删除</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </template>
      <!-- 底部图标栏 -->
      <div class="mail-sider-bottom">
        <el-icon><User /></el-icon>
        <el-icon><Setting /></el-icon>
      </div>
    </div>
    <!-- 右侧主内容区域 -->
    <div class="mail-content">
      <template v-if="!hasBindEmail">
        <!-- 未绑定时，右侧留空 -->
      </template>
      <template v-else>
        <!-- 已绑定邮箱时的邮件列表区 -->
        <div class="mail-toolbar">
          <el-input v-model="search" placeholder="输入搜索条件" size="small" class="mail-search" clearable />
          <div class="mail-actions">
            <el-button icon="el-icon-message" circle size="small" />
            <el-button icon="el-icon-star-off" circle size="small" />
            <el-button icon="el-icon-collection-tag" circle size="small" />
            <el-button icon="el-icon-copy-document" circle size="small" />
            <el-button icon="el-icon-delete" circle size="small" />
          </div>
        </div>
        <el-table :data="mails" border stripe size="small" style="margin-top:8px;">
          <el-table-column type="selection" width="36" />
          <el-table-column prop="from" label="发件人" min-width="140" />
          <el-table-column prop="subject" label="主题" min-width="180" />
          <el-table-column prop="receivedDate" label="时间" min-width="130">
            <template #default="{ row }">{{ formatDate(row.receivedDate) }}</template>
          </el-table-column>
          <el-table-column prop="previewText" label="摘要" min-width="200" />
        </el-table>
        <div style="padding:8px 0; display: flex; justify-content: flex-end;">
          <el-pagination
              background
              layout="total, prev, pager, next, jumper"
              :total="total"
              :page-size="pageSize"
              :current-page="currentPage"
              @current-change="handlePageChange"
          />
        </div>
      </template>
    </div>
    <!-- 绑定邮箱弹窗（新） -->
    <el-dialog v-model="dialogVisible" title="绑定邮箱" width="960px" :close-on-click-modal="false" top="120px">
      <el-row :gutter="36" class="mail-dialog-content">
        <el-col :span="13">
          <el-form :model="form" :rules="rules" ref="formRef" label-width="140px" size="default">
            <el-form-item label="接收服务器类型" prop="imapType">
              <el-select v-model="form.imapType" style="width: 100%;">
                <el-option label="IMAP" value="IMAP" />
                <el-option label="POP3" value="POP3" />
              </el-select>
            </el-form-item>
            <el-form-item label="邮件类型" prop="mailType">
              <el-select v-model="form.mailType" style="width: 100%;">
                <el-option label="其他邮箱" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" autocomplete="off" placeholder="请输入邮箱账号" />
            </el-form-item>
            <el-form-item label="授权码或密码" prop="password">
              <el-input v-model="form.password" type="password" autocomplete="off" show-password placeholder="请输入邮箱密码或授权码" />
            </el-form-item>
            <el-form-item label="IMAP服务器地址" prop="imapHost">
              <el-input v-model="form.imapHost" placeholder="请输入IMAP服务器地址" />
            </el-form-item>
            <el-form-item label="SMTP服务器地址" prop="smtpHost">
              <el-input v-model="form.smtpHost" placeholder="请输入SMTP服务器地址" />
            </el-form-item>
            <el-form-item label="邮箱账户名称" prop="accountName">
              <el-input v-model="form.accountName" placeholder="请输入邮箱账户名称" />
            </el-form-item>
            <el-form-item label="发件人显示名称" prop="senderName">
              <el-input v-model="form.senderName" placeholder="请输入发件人显示名称" />
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="11">
          <div class="tips-area">
            <div class="tips-title">温馨提示：</div>
            <div class="tips-content">
              <p>绑定邮箱之前，请到您原始web端邮箱的设置中：</p>
              <br>
              <p>1. 查找“收取选项”的类似字段，看到有“收取最近30天的邮件”、“收取最近90天的邮件”、“收取全部邮件”等这些选项，一定要选择“收取全部邮件”这个选项，否则会影响邮件的正常同步和收取。</p>
              <br>
              <p>2. 查找“邮件自动保存到已发送”的类似字段，一定要勾选这个选项。</p>
              <br>
              <p>3. 如果在邮箱设置中没有找到上述的两个设置，可以忽略。</p>
              <br>
              <p>4. 如果邮箱仅支持授权码或专用密码（后缀邮箱较常见）登录而非邮箱密码，请选择授权码。建议优先使用授权码。目前已知阿里云企业邮箱、qq邮箱、腾讯企业邮箱、网易/阿里企业邮箱等邮箱均支持授权码。</p>
              <br>
              <p>5. 常见邮箱（如qq邮箱、gmail邮箱、outlook/hotmail邮箱、yahoo邮箱、bossmail、263邮箱、华为邮箱、新浪个人/企业邮箱等）可以通过各自的服务器地址绑定。如有疑问，可以咨询对应的邮箱经理。</p>
            </div>
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="bindEmail">保 存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { bindMail, syncMailApi, queryMailApi } from "@/api/email/email.js";

const mails = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const search = ref("")

const hasBindEmail = ref(false)
const mailAccount = "lanyachem(jiang.zhu)"
const defaultOpeneds = ref(['common', mailAccount])

const dialogVisible = ref(false)
const formRef = ref()
const form = ref({
  imapType: 'IMAP',
  mailType: 'other',
  email: '',
  password: '',
  imapHost: 'imap.exmail.qq.com',
  smtpHost: 'smtp.exmail.qq.com',
  accountName: '',
  senderName: ''
})
const rules = {
  imapType: [{ required: true, message: '请选择服务器类型', trigger: 'blur' }],
  mailType: [{ required: true, message: '请选择邮件类型', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入邮箱密码或授权码', trigger: 'blur' }],
  imapHost: [{ required: true, message: '请输入IMAP服务器地址', trigger: 'blur' }],
  smtpHost: [{ required: true, message: '请输入SMTP服务器地址', trigger: 'blur' }],
  accountName: [{ required: false, message: '请输入账户名称', trigger: 'blur' }],
  senderName: [{ required: false, message: '请输入发件人显示名称', trigger: 'blur' }]
}

// 绑定邮箱，并自动同步邮件
function bindEmail() {
  formRef.value.validate(valid => {
    if (valid) {
      bindMail(form.value).then(res => {
        if (res.code === 200) {
          dialogVisible.value = false;
          hasBindEmail.value = true;
          ElMessage.success('绑定成功，正在自动同步邮件...');
          syncMailWithLoading();
        } else {
          ElMessage.error(res.message || '绑定失败！');
        }
      }).catch(() => {
        ElMessage.error('网络异常或服务错误！');
      });
    }
  });
}

// 同步远程邮件到本地（带loading效果）
function syncMailWithLoading() {
  const loading = ElLoading.service({ text: '正在同步邮件，请稍候...' });
  syncMailApi({
    email: form.value.email,
    password: form.value.password,
    imapHost: form.value.imapHost,
    syncCount: 500
  }).then(res => {
    loading.close();
    if (res.code === 200) {
      ElMessage.success(`同步完成，已拉取${res.data}封邮件！`);
      fetchLocalMails(1);
    } else {
      ElMessage.error(res.message || '同步失败！');
    }
  }).catch(() => {
    loading.close();
    ElMessage.error('网络异常或服务错误！');
  });
}

// 查询本地邮件（分页、搜索、文件夹切换均使用此方法）
function fetchLocalMails(page = 1) {
  queryMailApi({
    pageNum: page,
    pageSize: pageSize.value,
    keyword: search.value,
    folder: currentFolder.value
    // 可传 userId/accountEmail 参数
  }).then(res => {
    if (res.code === 200) {
      mails.value = res.data?.rows || res.data || [];
      total.value = res.data?.total || res.total || 0;
      currentPage.value = page;
    } else {
      ElMessage.error(res.message || '本地邮件查询失败！');
    }
  }).catch(() => {
    ElMessage.error('网络异常或服务错误！');
  });
}

function handlePageChange(page) {
  fetchLocalMails(page);
}

watch(search, () => {
  fetchLocalMails(1);
});

onMounted(() => {
  if (hasBindEmail.value) {
    fetchLocalMails(1);
  }
});

const currentFolder = ref("inbox")
function handleFolderSelect(name) {
  currentFolder.value = name;
  fetchLocalMails(1);
}

function formatDate(val) {
  if (!val) return '';
  const d = typeof val === 'string' ? new Date(val) : val;
  return d.toLocaleString('zh-CN', { hour12: false });
}

const mailIcon = 'https://img.icons8.com/color/144/000000/new-post.png'
</script>

<style scoped>
.mail-root {
  display: flex;
  height: 100vh;
  background: #fff;
}
.mail-sider {
  width: 250px;
  background: #f5f7fa;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.mail-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: calc(100vh - 80px);
  padding: 0 24px;
}
.mail-menu {
  background: transparent;
  border: none;
  margin-top: 10px;
}
.mail-sider-bottom {
  margin-top: auto;
  display: flex;
  justify-content: space-around;
  padding: 10px 0;
  border-top: 1px solid #e4e7ed;
  background: #f5f7fa;
}
.mail-content {
  flex: 1;
  padding: 18px 24px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}
.mail-toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.mail-search {
  flex: 1;
  margin-right: 12px;
}
</style>
